﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Domain.Models;
using Domain.DAL;
using Utilities;
using Casanova.Web;
using System.Data;

namespace WebApp.Users
{
    public partial class UserEdit : System.Web.UI.Page
    {

        #region Private Properties

        public int UserID
        {
            get
            {
                if (this.ViewState["ID"] != null)
                {
                    return Convert.ToInt32(this.ViewState["ID"]);
                }
                return MyConfig.NullNumber;
            }
            set
            {
                this.ViewState["ID"] = value.ToString();
            }
        }

        #endregion

        #region Event Handlers

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                (Master as SiteMaster).SelectedTab = "systemAdministrator";
                if (!IsPostBack)
                {
                    this.pageTitle.Text = Resources.Strings.SystemAdministrator + @"\" + Resources.Strings.UserManagement;
                    GetParam();

                    if (this.UserID == MyConfig.NullNumber)
                    {
                        LoadForm4New();
                    }
                    else
                    {
                        LoadFormForEdit();
                    }
                }
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                int result = MyConfig.NullNumber;

                if (this.UserID == MyConfig.NullNumber) //Insert
                {
                    result = InsertInfo();
                    if (result != MyConfig.NullNumber && result != 0)
                    {
                        Utility.ShowMessageBox(this.Page, Resources.Strings.SaveSuccess);
                    }
                    else if (result == 0)
                    {
                        Utility.ShowMessageBox(this.Page, Resources.Strings.DuplicateUsername);
                        return;
                    }
                    else
                    {
                        Utility.ShowMessageBox(this.Page, Resources.Strings.SaveFail);
                        return;
                    }
                }
                else     //Update
                {
                    result = UpdateInfo();
                    if (result != MyConfig.NullNumber && result != 0)
                    {
                        Utility.ShowMessageBox(this.Page, Resources.Strings.UpdateSuccess);
                    }
                    else if (result == 0)
                    {
                        Utility.ShowMessageBox(this.Page, Resources.Strings.DuplicateUsername);
                        return;
                    }
                    else
                    {
                        Utility.ShowMessageBox(this.Page, Resources.Strings.UpdateFail);
                        return;
                    }
                }
                Response.Redirect(this.ResolveUrl("~/Users/UserManagement.aspx"));
            }
            catch (Exception ex)
            {
                Utility.ShowMessageBox(this.Page, ex.ToString());
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect(this.ResolveUrl("~/Users/UserManagement.aspx"));
        }

        #endregion

        #region Private Methods

        private bool CheckValidate()
        {
            if (string.IsNullOrEmpty(txtUserName.Text.Trim()))
            {
                return false;
            }
            if (string.IsNullOrEmpty(txtPassword.Text.Trim()))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns>
        /// -1 fail
        /// 0 duplicate username
        /// >0 successfull
        /// </returns>
        private int InsertUser()
        {
            int result = MyConfig.NullNumber;
            try
            {
                if (!CheckValidate())
                {
                    result = MyConfig.NullNumber;
                }
                else
                {
                    UserDAO uDAO = UserDAO.GetInstance();
                    User u = GetUserInfo();
                    //Insert Employee.
                    result = uDAO.Insert(u);
                    if (result != MyConfig.NullNumber && result != 0)
                    {
                        this.UserID = result;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return result;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns>
        /// -1 fail
        /// 0 duplicate username
        /// >0 successfull
        /// </returns>
        private int UpdateUser()
        {
            int result = MyConfig.NullNumber;
            try
            {
                if (!CheckValidate())
                {
                    result = MyConfig.NullNumber;
                }
                UserDAO uDAO = UserDAO.GetInstance();
                User u = GetUserInfo();
                u.ID = UserID;
                //Update Employee.
                result = uDAO.Update(u);
            }
            catch (Exception)
            {
                throw;
            }
            return result;
        }

        private User GetUserInfo()
        {
            User u = new User();
            try
            {
                u.UserName = txtUserName.Text.Trim();
                u.Password = Utility.HashMD5(txtPassword.Text);
                if (!string.IsNullOrEmpty(rcbEmployee.SelectedValue))
                {
                    u.EmployeeID = Convert.ToInt32(rcbEmployee.SelectedValue);
                }
            }
            catch (Exception)
            {
                u = null;
                throw;
            }
            return u;
        }

        private void GetParam()
        {
            this.UserID = QueryStringUtility.GetInt32("ID", MyConfig.NullNumber);
        }

        private void LoadFormForEdit()
        {
            try
            {
                BindEmployees();
                BindRoles();

                UserDAO uDAO = UserDAO.GetInstance();
                User u = new User();
                u = uDAO.Get(this.UserID);

                if (u != null)
                {
                    txtUserName.Text = u.UserName;
                    //txtPassword.Text = u.Password;
                    rcbEmployee.SelectedValue = u.EmployeeID.ToString();
                }
                DataSet ds = new DataSet();
                ds = GetRolesForUser(this.UserID);
                SetMultiSelectedForCheckBoxList(cblRoles, ds, "RoleID");
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void LoadForm4New()
        {
            try
            {
                BindEmployees();
                BindRoles();
            }
            catch (Exception)
            {
                throw;
            }
        }

        private void BindEmployees()
        {
            DataSet ds = new DataSet();
            try
            {
                EmployeeDAO daoObject = EmployeeDAO.GetInstance();
                Employee e = new Employee();

                ds = daoObject.Search(e);
                if (ds != null)
                {
                    Utility.BindRadComboBox(rcbEmployee, ds, "Name", "ID", true);
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void BindRoles()
        {
            DataSet ds = new DataSet();
            try
            {
                RoleDAO daoObject = RoleDAO.GetInstance();
                Role r = new Role();

                ds = daoObject.Search(r);
                if (ds != null)
                {
                    Utility.BindCheckBoxList(cblRoles, ds, "RoleName", "ID");
                }
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
        }

        private void SetMultiSelectedForCheckBoxList(CheckBoxList theCheckBoxList, DataSet datasource, string columnName)
        {
            try
            {
                if (theCheckBoxList != null && datasource != null && datasource.Tables.Count > 0 && datasource.Tables[0].Rows.Count > 0)
                {
                    for (int i = 0; i < datasource.Tables[0].Rows.Count; i++)
                    {
                        foreach (ListItem item in theCheckBoxList.Items)
                        {
                            if(item.Value.Equals(datasource.Tables[0].Rows[i][columnName].ToString()))
                            {
                                item.Selected = true;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        private DataSet GetRolesForUser(int userID)
        {
            DataSet ds = new DataSet();
            try
            {
                RolesOfUsersDAO daoObject = RolesOfUsersDAO.GetInstance();

                ds = daoObject.GetByUser(userID);
            }
            catch (Exception)
            {
                ds.Dispose();
                throw;
            }
            return ds;
        }

        private bool DeleteRolesForUser(int userID)
        {
            bool result = false;
            try 
	        {
                RolesOfUsersDAO ruDAO = RolesOfUsersDAO.GetInstance();
                result = ruDAO.DeleteByUser(userID.ToString());
	        }
	        catch (Exception)
	        {
                result = false;
		        throw;
	        }
            return result;
        }

        private bool InsertRolesForUser(int userID)
        {
            bool result = true;
            try
            {
                foreach (ListItem item in cblRoles.Items)
                {
                    if (item.Selected)
                    {
                        RolesOfUser ru = new RolesOfUser();
                        ru.UserID = userID;
                        ru.RoleID = Convert.ToInt32(item.Value);

                        if (!InsertRoleForUser(ru))
                        {
                            DeleteRolesForUser(userID);
                            result = false;
                            break;
                        }
                    }   
                }
            }
            catch (Exception)
            {
                result = false;
                throw;
            }
            return result;
        }

        private bool InsertRoleForUser(RolesOfUser ru)
        {
            bool result = false;
            try
            {
                RolesOfUsersDAO ruDAO = RolesOfUsersDAO.GetInstance();
                if (ruDAO.Insert(ru) != MyConfig.NullNumber)
                {
                    result = true;
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }

        private int InsertInfo()
        {
            int result = MyConfig.NullNumber;
            try
            {
                result = InsertUser();
                if(result != MyConfig.NullNumber && result != 0)
                {
                    if (!InsertRolesForUser(this.UserID))
                    {
                        result = MyConfig.NullNumber;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return result;
        }

        private int UpdateInfo()
        {
            int result = MyConfig.NullNumber;
            try
            {
                result = UpdateUser();
                if (result != MyConfig.NullNumber && result != 0)
                {
                    if (DeleteRolesForUser(this.UserID))
                    {
                        if (!InsertRolesForUser(this.UserID))
                        {
                            result = MyConfig.NullNumber;
                        }
                    }
                    else
                    {
                        result = MyConfig.NullNumber;
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            return result;
        }

        #endregion
    }
}